package com.faintlight.controller;

import com.faintlight.exception.WarmException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@Tag(name = "文件上传", description = "图片上传接口")
public class FileController {

    @Value("${spring.servlet.multipart.location:./src/main/resources/static/upload}")
    private String uploadPath;

    @PostMapping
    @Operation(summary = "上传图片")
    public ResponseEntity<Map<String, String>> uploadImage(@RequestParam("image") MultipartFile file) {
        if (file.isEmpty()) {
            throw new WarmException("上传文件不能为空");
        }

        // 检查是否为图片
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new WarmException("仅支持图片上传");
        }

        // 生成唯一文件名
        String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                + "_" + UUID.randomUUID().toString().substring(0, 8) + ext;

        // 确保目录存在
        Path dirPath = Paths.get(uploadPath);
        if (!Files.exists(dirPath)) {
            try {
                Files.createDirectories(dirPath);
            } catch (IOException e) {
                throw new WarmException("创建上传目录失败: " + e.getMessage());
            }
        }

        // 保存路径
        Path filePath = dirPath.resolve(fileName);
        try {
            file.transferTo(filePath);
        } catch (IOException e) {
            throw new WarmException("文件保存失败: " + e.getMessage());
        }


        String fileUrl = "/api/static/upload/" + fileName;

        Map<String, String> result = new HashMap<>();
        result.put("url", fileUrl);
        result.put("filename", fileName);
        return ResponseEntity.ok(result);
    }
}